import 'package:hive/hive.dart';
import '../index.dart';
import 'apple_sign_in_service.dart';

class UserService {
  static const String _boxName = 'users';
  static const String _currentUserKey = 'current_user';

  /// 初始化用户服务
  static Future<void> initialize() async {
    // 注册适配器
    if (!Hive.isAdapterRegistered(0)) {
      Hive.registerAdapter(UserEntityAdapter());
    }

    // 打开用户数据盒子
    await Hive.openBox<UserEntity>(_boxName);
    await Hive.openBox(_currentUserKey);

    // 初始化默认用户
    await _initializeDefaultUsers();
  }

  /// 初始化默认用户
  static Future<void> _initializeDefaultUsers() async {
    final box = Hive.box<UserEntity>(_boxName);

    // 如果数据库为空，添加默认用户
    if (box.isEmpty) {
      for (final user in UserEntity.defaultUsers) {
        await box.put(user.username, user);
      }
    }
  }

  /// 用户登录
  static Future<UserEntity?> login(String username, String password) async {
    try {
      final box = Hive.box<UserEntity>(_boxName);
      final user = box.get(username);

      if (user != null && user.password == password) {
        // 保存当前登录用户
        await _setCurrentUser(user);

        print('登录成功: $user');
        return user;
      }
      return null;
    } catch (e) {
      print('登录失败: $e');
      return null;
    }
  }

  /// 苹果登录
  static Future<UserEntity?> signInWithApple() async {
    try {
      // 执行苹果登录
      final result = await AppleSignInService.signIn();

      if (result == null || !result.success) {
        print('苹果登录失败: ${result?.error}');
        return null;
      }

      // 检查是否已存在该苹果用户
      final appleUserId = 'apple_${result.userIdentifier}';
      UserEntity? existingUser = await getUserById(appleUserId);

      if (existingUser != null) {
        // 用户已存在，直接登录
        await _setCurrentUser(existingUser);
        print('苹果登录成功（已存在用户）: $existingUser');
        return existingUser;
      } else {
        // 创建新的苹果用户
        final newUser = AppleSignInService.createAppleUser(
          userIdentifier: result.userIdentifier!,
          email: result.email,
          displayName: result.displayName,
        );

        // 保存新用户
        final box = Hive.box<UserEntity>(_boxName);
        await box.put(newUser.username, newUser);

        // 设置为当前用户
        await _setCurrentUser(newUser);

        print('苹果登录成功（新用户）: $newUser');
        return newUser;
      }
    } catch (e) {
      print('苹果登录失败: $e');
      return null;
    }
  }

  /// 用户注册
  static Future<bool> register({
    required String username,
    required String password,
    String? avatar,
  }) async {
    try {
      final box = Hive.box<UserEntity>(_boxName);

      // 检查用户名长度限制
      if (username.length > 6) {
        return false;
      }

      // 检查用户名是否已存在
      if (box.containsKey(username)) {
        return false;
      }

      // 创建新用户
      final newUser = UserEntity(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        username: username,
        password: password,
        avatar: avatar ?? MyImages.mark,
        share: [],
        isVip: false,
        like: [],
        reportedPosts: [],
        reportedUsers: [],
        reportedChats: [],
      );

      // 保存用户
      await box.put(username, newUser);
      return true;
    } catch (e) {
      print('注册失败: $e');
      return false;
    }
  }

  /// 获取当前登录用户
  static UserEntity? getCurrentUser() {
    try {
      final box = Hive.box(_currentUserKey);
      final userData = box.get('user');
      if (userData != null) {
        return UserEntity.fromJson(Map<String, dynamic>.from(userData));
      }
      return null;
    } catch (e) {
      print('获取当前用户失败: $e');
      return null;
    }
  }

  /// 设置当前用户
  static Future<void> _setCurrentUser(UserEntity user) async {
    try {
      final box = Hive.box(_currentUserKey);
      await box.put('user', user.toJson());
    } catch (e) {
      print('设置当前用户失败: $e');
    }
  }

  /// 用户登出
  static Future<void> logout() async {
    try {
      final box = Hive.box(_currentUserKey);
      await box.clear();
    } catch (e) {
      print('登出失败: $e');
    }
  }

  /// 更新用户信息
  static Future<bool> updateUser(UserEntity user) async {
    try {
      final box = Hive.box<UserEntity>(_boxName);

      // 获取当前用户信息，检查用户名是否发生变化
      final currentUser = getCurrentUser();
      String? oldUsername;

      // 如果是当前用户且用户名发生变化，需要删除旧的用户记录
      if (currentUser?.id == user.id &&
          currentUser?.username != user.username) {
        oldUsername = currentUser?.username;
      } else {
        // 如果不是当前用户，通过ID查找原用户名
        for (final existingUser in box.values) {
          if (existingUser.id == user.id &&
              existingUser.username != user.username) {
            oldUsername = existingUser.username;
            break;
          }
        }
      }

      // 保存新的用户信息
      await box.put(user.username, user);

      // 如果用户名发生变化，删除旧的用户记录
      if (oldUsername != null && oldUsername != user.username) {
        await box.delete(oldUsername);
      }

      // 如果是当前用户，同时更新当前用户信息
      if (currentUser?.id == user.id) {
        await _setCurrentUser(user);
      }

      return true;
    } catch (e) {
      print('更新用户信息失败: $e');
      return false;
    }
  }

  /// 添加分享记录
  static Future<bool> addShare(String shareId) async {
    try {
      final currentUser = getCurrentUser();
      if (currentUser == null) return false;

      final updatedUser = currentUser.copyWith(
        share: [...currentUser.share, shareId],
      );

      return await updateUser(updatedUser);
    } catch (e) {
      print('添加分享记录失败: $e');
      return false;
    }
  }

  /// 修改会员
  static Future<bool> updateVip() async {
    try {
      final currentUser = getCurrentUser();
      if (currentUser == null) return false;

      final updatedUser = currentUser.copyWith(isVip: true);

      return await updateUser(updatedUser);
    } catch (e) {
      print('添加历史记录失败: $e');
      return false;
    }
  }

  /// 检查用户今天是否已经发布过分享
  static Future<bool> hasSharedToday() async {
    try {
      final currentUser = getCurrentUser();
      if (currentUser == null) return false;

      // 如果是VIP用户，不限制发布次数
      if (currentUser.isVip) return false;

      // 获取今天的日期字符串
      final today = DateTime.now();
      final todayStr =
          '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';

      // 检查用户今天是否已经发布过分享
      final shareBox = Hive.box<ShareEntity>('shares');
      for (final shareId in currentUser.share) {
        final shareEntity = shareBox.get(shareId);
        if (shareEntity != null) {
          final shareDate = shareEntity.date;
          final shareDateParsed = DateTime.parse(shareDate);
          final shareDateStr =
              '${shareDateParsed.year}-${shareDateParsed.month.toString().padLeft(2, '0')}-${shareDateParsed.day.toString().padLeft(2, '0')}';
          if (shareDateStr == todayStr) {
            return true; // 今天已经发布过
          }
        }
      }

      return false; // 今天还没有发布过
    } catch (e) {
      print('检查今日发布状态失败: $e');
      return false;
    }
  }

  /// 获取所有用户
  static List<UserEntity> getAllUsers() {
    try {
      final box = Hive.box<UserEntity>(_boxName);
      return box.values.toList();
    } catch (e) {
      print('获取所有用户失败: $e');
      return [];
    }
  }

  /// 检查用户名是否存在
  static bool isUsernameExists(String username) {
    try {
      final box = Hive.box<UserEntity>(_boxName);
      return box.containsKey(username);
    } catch (e) {
      print('检查用户名失败: $e');
      return false;
    }
  }

  /// 根据id获取用户
  static Future<UserEntity?> getUserById(String id) async {
    final box = Hive.box<UserEntity>(_boxName);
    // 遍历所有用户，找到匹配的id
    for (final user in box.values) {
      if (user.id == id) {
        return user;
      }
    }
    return null;
  }

  /// 删除用户账号
  static Future<bool> deleteAccount(String userId) async {
    try {
      final box = Hive.box<UserEntity>(_boxName);
      final currentUserBox = Hive.box(_currentUserKey);

      // 查找要删除的用户
      UserEntity? userToDelete;
      String? usernameToDelete;

      for (final entry in box.toMap().entries) {
        if (entry.value.id == userId) {
          userToDelete = entry.value;
          usernameToDelete = entry.key;
          break;
        }
      }

      if (userToDelete == null || usernameToDelete == null) {
        print('用户不存在: $userId');
        return false;
      }

      // 清理相关数据
      await _cleanupUserRelatedData(userId);

      // 删除用户数据
      await box.delete(usernameToDelete);

      // 如果删除的是当前用户，清除当前用户信息
      final currentUser = getCurrentUser();
      if (currentUser?.id == userId) {
        await currentUserBox.clear();
      }

      print('用户账号删除成功: $userId');
      return true;
    } catch (e) {
      print('删除用户账号失败: $e');
      return false;
    }
  }

  /// 清理用户相关数据
  static Future<void> _cleanupUserRelatedData(String userId) async {
    try {
      // 清理消息数据
      await _cleanupUserMessages(userId);

      // 清理时间胶囊数据
      await _cleanupUserTimeCapsules(userId);

      // 清理分享数据
      await _cleanupUserShares(userId);

      // 清理评论数据
      await _cleanupUserComments(userId);

      // 清理举报数据
      await _cleanupUserReports(userId);
    } catch (e) {
      print('清理用户相关数据失败: $e');
    }
  }

  /// 清理用户消息
  static Future<void> _cleanupUserMessages(String userId) async {
    try {
      final messageBox = Hive.box('messages');
      final messagesToDelete = <String>[];

      for (final entry in messageBox.toMap().entries) {
        final message = entry.value;
        if (message is Map &&
            (message['senderId'] == userId ||
                message['receiverId'] == userId)) {
          messagesToDelete.add(entry.key);
        }
      }

      for (final messageId in messagesToDelete) {
        await messageBox.delete(messageId);
      }
    } catch (e) {
      print('清理用户消息失败: $e');
    }
  }

  /// 清理用户时间胶囊
  static Future<void> _cleanupUserTimeCapsules(String userId) async {
    try {
      final timeCapsuleBox = Hive.box('time_capsules');
      final capsulestoDelete = <String>[];

      for (final entry in timeCapsuleBox.toMap().entries) {
        final capsule = entry.value;
        if (capsule is Map && capsule['userId'] == userId) {
          capsulestoDelete.add(entry.key);
        }
      }

      for (final capsuleId in capsulestoDelete) {
        await timeCapsuleBox.delete(capsuleId);
      }
    } catch (e) {
      print('清理用户时间胶囊失败: $e');
    }
  }

  /// 清理用户分享
  static Future<void> _cleanupUserShares(String userId) async {
    try {
      final userToDelete = await getUserById(userId);
      if (userToDelete == null) return;

      final shareBox = Hive.box('shares');

      // 删除用户创建的分享
      for (final shareId in userToDelete.share) {
        await shareBox.delete(shareId);
      }
    } catch (e) {
      print('清理用户分享失败: $e');
    }
  }

  /// 清理用户评论
  static Future<void> _cleanupUserComments(String userId) async {
    try {
      final commentBox = Hive.box('comments');
      final commentsToDelete = <String>[];

      for (final entry in commentBox.toMap().entries) {
        final comment = entry.value;
        if (comment is Map && comment['userId'] == userId) {
          commentsToDelete.add(entry.key);
        }
      }

      for (final commentId in commentsToDelete) {
        await commentBox.delete(commentId);
      }
    } catch (e) {
      print('清理用户评论失败: $e');
    }
  }

  /// 清理用户举报
  static Future<void> _cleanupUserReports(String userId) async {
    try {
      final reportBox = Hive.box('reports');
      final reportsToDelete = <String>[];

      for (final entry in reportBox.toMap().entries) {
        final report = entry.value;
        if (report is Map &&
            (report['reporterId'] == userId || report['targetId'] == userId)) {
          reportsToDelete.add(entry.key);
        }
      }

      for (final reportId in reportsToDelete) {
        await reportBox.delete(reportId);
      }
    } catch (e) {
      print('清理用户举报失败: $e');
    }
  }
}
